package edu.zut.main.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

//一对一的客户端  服务器交互
//一对一    客户端与服务器交互时，利用循环一直通信，直到一方说再见，才断开连接
// 如果一对多  一个服务器  多个客户端  利用线程进行模拟    参考售票或转账
//基于tcp的客户端
public class TcpClient {
    public static void main(String[] args) throws IOException {

        //客户端需要根据ip以及端口访问服务器的应用程序
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        //基于ip + 端口创建socket连接
        Socket socket = new Socket(inetAddress,9999);
//        System.out.println("socket = " + socket);
        System.out.println("连接服务器成功");
        //通过io进行操作   模拟发送信息到服务器
        OutputStream os = socket.getOutputStream();
        os.write("nice to meet you,i am client!!!!".getBytes());
        //断开输出流
        socket.shutdownOutput();
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1){
            System.out.println(new String(buffer,0,len));
        }

        is.close();
        os.close();
        socket.close();

    }
}

//基于tcp的服务器端
class TcpServer{
    public static void main(String[] args) throws IOException {
        //根据端口指定一个serverSocket   服务器的ip是多少？127.0.0.1
        System.out.println("等待客户端连接.....");
        ServerSocket serverSocket = new ServerSocket(9999);
        //服务器是等待客户端连接的  accept 会自动监听客户端连接，只要客户端发送连接请求，就会自动响应
        Socket socket = serverSocket.accept();
        System.out.println("连接成功......");
//        System.out.println("socket = " + socket);
//        System.out.println(socket.getInetAddress());
        //通过io进行操作
        InputStream is = socket.getInputStream();

        byte[] buffer = new byte[521];

        int len;
        while ((len = is.read(buffer)) != -1){
            System.out.println(new String(buffer,0,len));
        }
        //断开输入流
        socket.shutdownInput();
        //服务器给客户端一个反馈
        OutputStream os = socket.getOutputStream();
        os.write("nice to meet you too, i am server".getBytes());

        os.close();
        is.close();
        socket.close();
        serverSocket.close();

    }
}

